﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Dictionary.Core;

namespace WebCrawler
{
    public partial class MainForm : Form
    {
        public Category selectedCategory = null;

        public MainForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Method config and init form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            reloadForm();
        }
        /// <summary>
        /// Load all category to listbox category
        /// </summary>
        private void reloadForm()
        {
            // reset form
            this.selectedCategory = null;
            txtNameCategory.Clear();
            txtUrlCategorySource.Clear();
            txtRegularExp.Clear();
            txtCreated.Clear();
            txtUpdated.Clear();
            // load all source
            List<Source> listSource = Source.selectAll();
            listBoxSource.DataSource = listSource;
            listBoxSource.DisplayMember = "url";
            listBoxSource.ValueMember = "id";
            // load all category in source
            if (listBoxSource.SelectedItems.Count > 0)
            {
                int source_id = Convert.ToInt16(listBoxSource.SelectedValue.ToString());
                List<Category> listCategory = Category.selectAll(source_id);
                listBoxCategory.DataSource = listCategory;
                listBoxCategory.DisplayMember = "title";
                listBoxCategory.ValueMember = "id";
            }
            // display all vocal in category selected
            if (listBoxCategory.SelectedItems.Count > 0)
            {
                int category_id = Convert.ToInt16(listBoxCategory.SelectedValue.ToString());
                List<Vocabulary> listVocab = Vocabulary.selectAll(category_id);
                listBoxVocab.DataSource = listVocab;
                listBoxVocab.DisplayMember = "value";
                listBoxVocab.ValueMember = "id";
            }

            // load all to language
            comboBoxTranslateTo.Items.AddRange(Translate.getLanguages());
            comboBoxTranslateTo.Text = "Vietnamese";
        }
        /// <summary>
        /// View all category in source
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxSource_Click(object sender, EventArgs e)
        {
            if (listBoxSource.SelectedItems.Count > 0)
            {
                int source_id = Convert.ToInt16(listBoxSource.SelectedValue.ToString());
                List<Category> listCategory = Category.selectAll(source_id);
                listBoxCategory.DataSource = listCategory;
                listBoxCategory.DisplayMember = "title";
                listBoxCategory.ValueMember = "id";

                this.selectedCategory = null;
            }
        }
        /// <summary>
        /// View all vocab in category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxCategory_Click(object sender, EventArgs e)
        {
            if (listBoxCategory.SelectedItems.Count > 0)
            {
                int category_id = Convert.ToInt16(listBoxCategory.SelectedValue.ToString());

                if (this.selectedCategory == null)
                    this.selectedCategory = new Category();
                this.selectedCategory.id = category_id;
                this.selectedCategory.select();
                // display detail category
                txtNameCategory.Text = this.selectedCategory.title;
                txtUrlCategorySource.Text = this.selectedCategory.link;
                txtRegularExp.Text = this.selectedCategory.regular_exp;
                txtCreated.Text = this.selectedCategory.created;
                txtUpdated.Text = this.selectedCategory.updated;
                // display all vocal in category selected
                List<Vocabulary> listVocab = Vocabulary.selectAll(category_id);
                listBoxVocab.DataSource = listVocab;
                listBoxVocab.DisplayMember = "value";
                listBoxVocab.ValueMember = "id";
            }
            
        }
        /// <summary>
        /// Create new Category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            Category newCategory = new Category(txtNameCategory.Text.ToString().Trim(), txtUrlCategorySource.Text.ToString().Trim(),txtRegularExp.Text.ToString().Trim());
            if(!newCategory.insert())
                MessageBox.Show("Have error when insert this category.\nPlease try again!", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
                reloadForm();
        }

        /// <summary>
        /// Update Category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (this.selectedCategory != null)
            {
                this.selectedCategory.link = txtUrlCategorySource.Text.ToString().Trim();
                this.selectedCategory.title = txtNameCategory.Text.ToString().Trim();
                this.selectedCategory.regular_exp = txtRegularExp.Text.ToString().Trim();
                if (!this.selectedCategory.update())
                    MessageBox.Show("Have error when update this category.\n(Maybe URL had in database.)\nPlease try again!", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    reloadForm();
            }
            else
                MessageBox.Show("Please select category you want to edit!");
        }

        /// <summary>
        /// Delete Category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.selectedCategory != null)
            {
                if(MessageBox.Show("Do you want to delete this Category and all Vocab inside?","Confirm:", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    if (!this.selectedCategory.delete())
                        MessageBox.Show("Have error when delete this category.\nPlease try again!","Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    else
                        reloadForm();
                }
            }
        }

        /// <summary>
        /// Reget all Vocab into category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetData_Click(object sender, EventArgs e)
        {
            if (this.selectedCategory != null)
            {
                if (MessageBox.Show("Do you want to reget Vocab inside category?\n(All Vocab current inside category will be delete.)", "Confirm:", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    // get new data
                    List<Vocabulary> listVocab = this.selectedCategory.regetVocab();
                    MessageBox.Show("System have saved " + listVocab.Count + " item(s).");
                    // display listbox vocab
                    listBoxVocab.DataSource = listVocab;
                    listBoxVocab.DisplayMember = "value";
                    listBoxVocab.ValueMember = "value";
                }
            }
        }

        /// <summary>
        /// to backup database to sql file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBackData_Click(object sender, EventArgs e)
        {
            DateTime Time = DateTime.Now;
            int year = Time.Year;
            int month = Time.Month;
            int day = Time.Day;
            int hour = Time.Hour;
            int minute = Time.Minute;
            int second = Time.Second;
            int millisecond = Time.Millisecond;
            String nameFile = year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";

            saveFileSqlDialog.FileName = nameFile;
            saveFileSqlDialog.ShowDialog();
        }
        /// <summary>
        /// Begin save file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveFileSqlDialog_FileOk(object sender, CancelEventArgs e)
        {
            String strPath = saveFileSqlDialog.FileName;
            SQLHelper sqlHelper = new SQLHelper();
            sqlHelper.Backup(strPath);
        }

        /// <summary>
        /// Open management form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnManagement_Click(object sender, EventArgs e)
        {
            GetDataForm frmManagement = new GetDataForm();
            frmManagement.ShowDialog();
        }
        /// <summary>
        /// To export data in Category to file .txt
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExportData_Click(object sender, EventArgs e)
        {
            if (this.selectedCategory != null)
            {
                saveFileExportDataDialog.FileName = txtNameCategory.Text.Trim() + ".txt";
                saveFileExportDataDialog.ShowDialog();
            }
        }
        /// <summary>
        /// to begin save file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveFileExportDataDialog_FileOk(object sender, CancelEventArgs e)
        {
            String strPath = saveFileExportDataDialog.FileName;
            String strContent = "";

            strContent += this.selectedCategory.title + "\r\n";
            strContent += this.selectedCategory.link + "\r\n";
            strContent += "--------------------------------\r\n";
            foreach (Vocabulary item in Vocabulary.selectAll(this.selectedCategory.id))
            {
                strContent += item.value + "\r\n";
            }

            File.WriteAllText(strPath, strContent);
        }
        /// <summary>
        /// method to enable or disable group category management
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBoxCategoryManagement_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxCategoryManagement.Enabled = checkBoxCategoryManagement.Checked;
        }
        /// <summary>
        /// To translate vocab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxVocab_DoubleClick(object sender, EventArgs e)
        {
            Translate translate = new Translate("English",comboBoxTranslateTo.Text,listBoxVocab.Text);
            txtTranslateOutput.Text = listBoxVocab.Text +  "\r\n" + translate.toTranslate();
        }
        /// <summary>
        /// Button to refresh form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            reloadForm();
        }
        /// <summary>
        /// Method to search category in side source
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSearchCategory_TextChanged(object sender, EventArgs e)
        {
            if (listBoxSource.SelectedItems.Count > 0)
            {
                int source_id = Convert.ToInt16(listBoxSource.SelectedValue.ToString());
                List<Category> listCategory = Category.search(source_id, txtSearchCategory.Text.ToString().Trim());
                listBoxCategory.DataSource = listCategory;
                listBoxCategory.DisplayMember = "title";
                listBoxCategory.ValueMember = "id";
            }
        }
        /// <summary>
        /// Method to search vocab in side Category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSearchVocab_TextChanged(object sender, EventArgs e)
        {
            if (listBoxCategory.SelectedItems.Count > 0)
            {
                int category_id = 0;
                if (checkBoxSearchVocab.Checked)
                    category_id = Convert.ToInt16(listBoxCategory.SelectedValue.ToString());
                List<Vocabulary> listVocab = Vocabulary.search(category_id, txtSearchVocab.Text.ToString().Trim());
                listBoxVocab.DataSource = listVocab;
                listBoxVocab.DisplayMember = "value";
                listBoxVocab.ValueMember = "id";
            }
        }
        /// <summary>
        /// Method to translate title category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxCategory_DoubleClick(object sender, EventArgs e)
        {
            Translate translate = new Translate("English", comboBoxTranslateTo.Text, listBoxCategory.Text);
            txtTranslateOutput.Text = listBoxCategory.Text + "\r\n" + translate.toTranslate();
        }
        /// <summary>
        /// Update status of database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerUpdateStatus_Tick(object sender, EventArgs e)
        {
            lblStatus.Text = DateTime.Now.ToLongTimeString() + "\nCategory count : " + Category.count().ToString() + " - Vocab count : " + Vocabulary.count().ToString();
        }
    }
}
